package com.oa.erp.ass.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.erp.ass.dto.CategoryTreeDto;
import com.oa.erp.ass.entity.AssetCategory;
import com.oa.erp.ass.service.AssetCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mdp.core.utils.BaseUtils.map;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController
@RequestMapping(value = "/*/oa/erp/ass/assetCategory")
@Api(tags = {"ass_asset_category-操作接口"})
public class AssetCategoryController {

    static Logger logger = LoggerFactory.getLogger(AssetCategoryController.class);

    @Autowired
    private AssetCategoryService assetCategoryService;

    @ApiOperation(value = "ass_asset_category-查询列表", notes = " ")
    @ApiEntityParams(AssetCategory.class)
    @ApiResponses({@ApiResponse(code = 200, response = AssetCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listAssetCategory(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "categoryIds");
        params.put("branchId", user.getBranchId());
        QueryWrapper<AssetCategory> qw = QueryTools.initQueryWrapper(AssetCategory.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = assetCategoryService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    @ApiOperation(value = "查询ass_asset_category信息列表树形结构", notes = "查询ass_asset_category信息列表树形结构")
    @RequestMapping(value = "/getAssetCategoryTree", method = RequestMethod.GET)
    public Result listAssetCategoryByTree(@RequestParam Map<String, Object> assetCategory) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(assetCategory, "categoryIds");
        QueryWrapper<AssetCategory> qw = QueryTools.initQueryWrapper(AssetCategory.class, assetCategory);
        IPage page = QueryTools.initPage(assetCategory);
        List<CategoryTreeDto> assetCategoryList = assetCategoryService.listAssetCategoryByTree(page, qw, user.getBranchId());    //列出AssetCategory列表
        return Result.ok("query-ok", "查询成功").setData(assetCategoryList);
    }


    @ApiOperation(value = "ass_asset_category-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addAssetCategory(@RequestBody AssetCategory assetCategory) {
        User user = LoginUtils.getCurrentUserInfo();
        if (StringUtils.isEmpty(assetCategory.getCategoryId())) {
            assetCategory.setCategoryId(assetCategoryService.createKey("categoryId"));
        } else {
            AssetCategory assetCategoryQuery = new AssetCategory(assetCategory.getCategoryId(), user.getBranchId());
            if (assetCategoryService.countByWhere(assetCategoryQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        assetCategory.setBranchId(user.getBranchId());
        assetCategoryService.insertAssetCategory(assetCategory);

        return Result.ok("add-ok", "添加成功！").setData(assetCategory);
    }

    @ApiOperation(value = "ass_asset_category-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delAssetCategory(@RequestBody AssetCategory assetCategory) {
        //查询是否下面还有子分类
        if (!StringUtils.hasText(assetCategory.getBranchId())) {
            return Result.error("branchId-not-exists", "机构参数不能为空");
        }
        if (!StringUtils.hasText(assetCategory.getCategoryId())) {
            return Result.error("categoryId-not-exists", "分类编号参数不能为空");
        }
        User user = LoginUtils.getCurrentUserInfo();
        Map<String, Object> param = new HashMap<>();
        param.put("categoryId", assetCategory.getCategoryId());
        param.put("branchId", assetCategory.getBranchId());
        List<AssetCategory> assetCategoryList = assetCategoryService.selectIsExitOtherCategory(param);
        if (assetCategoryList.size() > 0) {
            return Result.error("该分类下还存在其他分类");
        }
        assetCategoryService.deleteByPk(assetCategory);

        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "ass_asset_category-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editAssetCategory(@RequestBody AssetCategory assetCategory) {
        if (!StringUtils.hasText(assetCategory.getBranchId())) {
            return Result.error("branchId-not-exists", "机构参数不能为空");
        }
        if (!StringUtils.hasText(assetCategory.getCategoryId())) {
            return Result.error("categoryId-not-exists", "分类编号参数不能为空");
        }
        assetCategoryService.updateByPk(assetCategory);

        return Result.ok("edit-ok", "修改成功！").setData(assetCategory);
    }

    @ApiOperation(value = "ass_asset_category-批量修改某些字段", notes = "")
    @ApiEntityParams(value = AssetCategory.class, props = {}, remark = "ass_asset_category", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = AssetCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        assetCategoryService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "ass_asset_category-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelAssetCategory(@RequestBody List<AssetCategory> assetCategorys) {
        User user = LoginUtils.getCurrentUserInfo();
        if (assetCategorys.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<AssetCategory> datasDb = assetCategoryService.listByIds(assetCategorys.stream().map(i -> map("categoryId", i.getCategoryId(), "branchId", i.getBranchId())).collect(Collectors.toList()));

        List<AssetCategory> no = new ArrayList<>();
        List<AssetCategory> can = new ArrayList<>(datasDb);
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            assetCategoryService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getCategoryId() + " " + i.getBranchId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "ass_asset_category-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = AssetCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(AssetCategory assetCategory) {
        AssetCategory data = (AssetCategory) assetCategoryService.getById(assetCategory);
        return Result.ok().setData(data);
    }

}
